import  pandas as pd
import matplotlib.pyplot as plt

#读取target文件
target_path = 'SampleTarget2.csv'
df_tar = pd.read_csv(target_path)
#读取clz
path_ft_ls = list(df_tar.columns)[2:]
df_clz = pd.DataFrame()
df_clz['trading_day'] = df_tar['trading_day']
df_clz['timestamp'] = df_tar['timestamp']
for name in path_ft_ls:
    # name = path_ft_ls[0]
    df_t = pd.read_feather('1m/1m/' + name + '.ft')
    df_t = df_t.merge(df_clz[['trading_day', 'timestamp']], on=['trading_day'], how='left', suffixes=('', '_clz'))
    df_t = df_t[df_t['timestamp'] <= df_t['timestamp_clz']]
    df_t = df_t.groupby(by=['trading_day', 'timestamp_clz'])[['clz']].last()
    df_t.reset_index(inplace=True)
    df_t.rename(columns={'timestamp_clz':'timestamp', 'clz': name}, inplace=True)
    df_clz = df_clz.merge(df_t[['trading_day', 'timestamp', name]], on=['trading_day', 'timestamp'], how='left')


#读取每天收盘的clz
df_clz_1459 = pd.DataFrame()
df_clz_1459['trading_day'] = df_tar['trading_day']
df_clz_1459['timestamp'] = 145900
for name in path_ft_ls:
    # name = path_ft_ls[0]
    df_t = pd.read_feather('1m/1m/' + name + '.ft')
    df_t = df_t.groupby(by=['trading_day'])[['clz']].last()
    df_t.rename(columns = {'clz':name},inplace=True)
    # df_clz_1459[name] = df_t['clz']
    df_clz_1459 = df_clz_1459.merge(df_t, on=['trading_day'], how='left')
    # df_clz_1459.rename(columns = {'clz':name},inplace=True)

def SetTimeIndex(df_tar):
    df_tar.loc[df_tar['timestamp'] > 145900, 'trading_day'] = df_tar.shift(-1)[df_tar['timestamp'] > 145900]['trading_day'].values
    df_tar.set_index(keys=['trading_day'], inplace=True)
    df_tar.index = pd.DatetimeIndex(df_tar.index.astype(int).astype(str))
    df_tar.drop(labels=['timestamp'], inplace=True, axis=1)
    return df_tar
df_tar = SetTimeIndex(df_tar)
df_clz = SetTimeIndex(df_clz)
df_clz_1459 = SetTimeIndex(df_clz_1459)

df_clz_1459 = df_clz_1459.loc[df_tar.index]

df_clz_1459 = df_clz_1459.loc[~df_clz_1459.index.duplicated(keep='last')]
df_tar_last = df_tar.loc[~df_tar.index.duplicated(keep='last')]
# pnl = 昨日target * (今日clz / 昨日clz - 1)
# turnover = 今日target - 昨日target * (今日clz / 昨日clz)

pnl = (df_tar_last.shift(1)*df_clz_1459/df_clz_1459.shift(1) - df_tar_last.shift(1)).sum(axis = 1)

turnover = (df_tar - df_tar.shift(1)*df_clz/df_clz.shift(1)).abs().sum(axis = 1)
turnover = turnover.groupby(by=['trading_day']).last()

pnl_net = pnl - turnover*3*10**(-4)

Sharp = pnl_net.mean() / pnl_net.std() * 15.8
lower = 1
if df_tar.iloc[0, :].sum() > 5:
    lower = 100e4
TurnOver = turnover.mean() / lower
AveLeverage = df_tar.sum(axis = 1).abs().mean() / lower

plt.figure('pnl')
plt.title('Sharp:{:.2f},TurnOver:{:.2f},AveLeverage:{:.2f}'.format(Sharp, TurnOver, AveLeverage))
plt.plot(pnl.cumsum(), label = 'pnl')
plt.plot(pnl_net.cumsum(), label = 'pnl_net')
plt.legend()
plt.show()

